package xjh.him.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;

import com.xjh.him.R;

import java.util.Objects;

import xjh.him.common.SharedData;
import xjh.him.entity.User;
import xjh.him.netty.codec.Packet;
import xjh.him.netty.dto.FriendDto;
import xjh.him.util.GlideUtil;
import xjh.him.util.ToastUtil;

public class SearchResultActivity extends Activity {
    private User user;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_result);

        initViewContent();
        onApplyFriendBtnClick();
    }

    private void initViewContent() {
        Toolbar toolbar = findViewById(R.id.search_title);
        TextView nameText = findViewById(R.id.search_user_name);
        ImageView avatarImage = findViewById(R.id.search_user_avatar);
        ImageView sexImage = findViewById(R.id.search_user_sex);
        TextView landText = findViewById(R.id.search_user_land);
        TextView signatureText = findViewById(R.id.search_user_sn);

        toolbar.setNavigationIcon(R.drawable.icon_back);
        toolbar.setNavigationOnClickListener((view) -> finish());

        Intent intent = getIntent();
        user = (User) intent.getSerializableExtra("chatter");
        Objects.requireNonNull(user, "user is null");
        nameText.setText(user.getNickname());
        GlideUtil.loadImage(this, user.getAvatarUrl(), avatarImage, GlideUtil.defaultRoundedAvatarOpt());
        if ("女".equals(user.getSex()))
            sexImage.setSelected(true);
        else if ("".equals(user.getSex()))
            sexImage.setVisibility(View.INVISIBLE);
        landText.setText("地区：" + user.getBirthland());
        signatureText.setText(user.getSignature());
    }

    private void onApplyFriendBtnClick() {
        Button applyBtn = findViewById(R.id.apply_friend_btn);
        applyBtn.setOnClickListener((view) -> {
            FriendDto.ApplyForFriendReq req = new FriendDto.ApplyForFriendReq();
            req.setApplyId(SharedData.me.getId());
            req.setAppliedId(user.getId());
            SharedData.client.sendMsg(Packet.create(FriendDto.ApplyForFriendReq.class, req));
            Object obj = SharedData.future.get();
            if (obj instanceof FriendDto.ApplyForFriendResp) {
                ToastUtil.show(this, "已发送好友申请");
            }else {
                ToastUtil.show(this, "未知错误");
            }
            finish();
        });
    }
}
